from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from django.db import transaction
from django.db.models import Q, Count, Avg
from django.utils import timezone
from django.http import HttpResponse
from .models import Enrollment
from apps.courses.models import Course
from apps.users.models import User
from .serializers import (
    EnrollmentSerializer, EnrollmentListSerializer,
    EnrollmentDetailSerializer, TeacherEnrollmentListSerializer,
    AdminEnrollmentListSerializer, EnrollmentGradeSerializer
)
import logging
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill
from io import BytesIO
import datetime

logger = logging.getLogger(__name__)


class EnrollmentView(APIView):
    """选课视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """学生选课"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'student':
                return Response({
                    'code': 403,
                    'message': '只有学生可以选课'
                }, status=status.HTTP_403_FORBIDDEN)

            course_id = request.data.get('course_id')
            if not course_id:
                return Response({
                    'code': 400,
                    'message': '课程ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 检查课程是否存在
            try:
                course = Course.objects.get(id=course_id)
            except Course.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '课程不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 检查课程状态
            if course.status != 'active':
                return Response({
                    'code': 400,
                    'message': '该课程未开放选课'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 检查是否已经选过该课程
            existing_enrollment = Enrollment.objects.filter(
                student_id=user_id,
                course_id=course_id,
                status__in=['enrolled', 'completed']
            ).first()

            if existing_enrollment:
                if existing_enrollment.status == 'enrolled':
                    return Response({
                        'code': 400,
                        'message': '您已经选择了该课程'
                    }, status=status.HTTP_400_BAD_REQUEST)
                elif existing_enrollment.status == 'completed':
                    return Response({
                        'code': 400,
                        'message': '您已经完成了该课程'
                    }, status=status.HTTP_400_BAD_REQUEST)

            # 检查课程容量
            if course.enrolled_count >= course.capacity:
                return Response({
                    'code': 400,
                    'message': '该课程已满员'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 创建选课记录
            with transaction.atomic():
                # 如果之前退选过，更新状态
                dropped_enrollment = Enrollment.objects.filter(
                    student_id=user_id,
                    course_id=course_id,
                    status='dropped'
                ).first()

                if dropped_enrollment:
                    dropped_enrollment.status = 'enrolled'
                    dropped_enrollment.enrollment_date = timezone.now()
                    dropped_enrollment.save()
                    enrollment = dropped_enrollment
                else:
                    enrollment = Enrollment.objects.create(
                        student_id=user_id,
                        course_id=course_id,
                        status='enrolled'
                    )

                # 更新课程选课人数
                course.enrolled_count = Enrollment.objects.filter(
                    course=course,
                    status='enrolled'
                ).count()
                course.save(update_fields=['enrolled_count'])

            return Response({
                'code': 200,
                'message': '选课成功',
                'data': {
                    'enrollment_id': enrollment.id,
                    'course_name': course.course_name,
                    'teacher_name': course.teacher.real_name
                }
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"选课失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '选课失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def delete(self, request):
        """学生退课"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'student':
                return Response({
                    'code': 403,
                    'message': '只有学生可以退课'
                }, status=status.HTTP_403_FORBIDDEN)

            course_id = request.data.get('course_id')
            if not course_id:
                return Response({
                    'code': 400,
                    'message': '课程ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 查找选课记录
            try:
                enrollment = Enrollment.objects.get(
                    student_id=user_id,
                    course_id=course_id,
                    status='enrolled'
                )
            except Enrollment.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '未找到选课记录'
                }, status=status.HTTP_404_NOT_FOUND)

            # 检查是否已经有成绩
            if enrollment.total_score is not None:
                return Response({
                    'code': 400,
                    'message': '已有成绩的课程不能退选'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 更新选课状态为退选
            with transaction.atomic():
                enrollment.status = 'dropped'
                enrollment.save()

                # 更新课程选课人数
                course = enrollment.course
                course.enrolled_count = Enrollment.objects.filter(
                    course=course,
                    status='enrolled'
                ).count()
                course.save(update_fields=['enrolled_count'])

            return Response({
                'code': 200,
                'message': '退课成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"退课失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '退课失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class StudentEnrollmentListView(APIView):
    """学生选课列表视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取学生的选课列表"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'student':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            enrollment_status = request.GET.get('status', '')
            semester = request.GET.get('semester', '')
            ordering = request.GET.get('ordering', '-enrollment_date')

            # 构建查询集
            queryset = Enrollment.objects.filter(
                student_id=user_id
            ).select_related('course', 'course__teacher')

            if enrollment_status:
                queryset = queryset.filter(status=enrollment_status)

            if semester:
                queryset = queryset.filter(course__semester=semester)

            # 排序
            if ordering:
                queryset = queryset.order_by(ordering)
            else:
                queryset = queryset.order_by('-enrollment_date')

            # 计算总数
            total = queryset.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            enrollments = queryset[start:end]

            # 序列化数据
            serializer = EnrollmentListSerializer(enrollments, many=True)

            response_data = {
                'enrollments': serializer.data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }

            return Response({
                'code': 200,
                'message': '获取选课列表成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取选课列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取选课列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class TeacherEnrollmentListView(APIView):
    """教师查看自己课程的选课学生列表"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取教师课程的选课学生列表"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'teacher':
                return Response({
                    'code': 403,
                    'message': '只有教师可以查看选课学生'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            student_search = request.GET.get('student_search', '').strip()
            course_search = request.GET.get('course_search', '').strip()
            enrollment_status = request.GET.get('status', '')
            semester = request.GET.get('semester', '')
            grade_status = request.GET.get('grade_status', '')
            ordering = request.GET.get('ordering', '-enrollment_date')

            # 构建查询集 - 只查询该教师的课程
            queryset = Enrollment.objects.filter(
                course__teacher_id=user_id
            ).select_related('course', 'course__teacher', 'student')

            # 应用筛选条件
            if student_search:
                queryset = queryset.filter(
                    Q(student__real_name__icontains=student_search) |
                    Q(student__student_id__icontains=student_search)
                )

            if course_search:
                queryset = queryset.filter(
                    Q(course__course_name__icontains=course_search) |
                    Q(course__course_code__icontains=course_search)
                )

            if enrollment_status:
                queryset = queryset.filter(status=enrollment_status)

            if semester:
                queryset = queryset.filter(course__semester=semester)

            if grade_status:
                if grade_status == 'graded':
                    queryset = queryset.filter(total_score__isnull=False)
                elif grade_status == 'ungraded':
                    queryset = queryset.filter(total_score__isnull=True)

            # 排序
            if ordering:
                queryset = queryset.order_by(ordering)
            else:
                queryset = queryset.order_by('-enrollment_date')

            # 计算总数
            total = queryset.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            enrollments = queryset[start:end]

            # 序列化数据
            serializer = TeacherEnrollmentListSerializer(enrollments, many=True)

            response_data = {
                'enrollments': serializer.data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }

            return Response({
                'code': 200,
                'message': '获取选课学生列表成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取选课学生列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取选课学生列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class AdminEnrollmentListView(APIView):
    """管理员查看所有选课记录"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取所有选课记录"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '只有管理员可以查看所有选课记录'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            student_search = request.GET.get('student_search', '').strip()
            course_search = request.GET.get('course_search', '').strip()
            teacher_id = request.GET.get('teacher_id', '')
            enrollment_status = request.GET.get('status', '')
            semester = request.GET.get('semester', '')
            grade_status = request.GET.get('grade_status', '')
            ordering = request.GET.get('ordering', '-enrollment_date')

            # 构建查询集
            queryset = Enrollment.objects.select_related(
                'course', 'course__teacher', 'student'
            )

            # 应用筛选条件
            if student_search:
                queryset = queryset.filter(
                    Q(student__real_name__icontains=student_search) |
                    Q(student__student_id__icontains=student_search)
                )

            if course_search:
                queryset = queryset.filter(
                    Q(course__course_name__icontains=course_search) |
                    Q(course__course_code__icontains=course_search)
                )

            if teacher_id:
                queryset = queryset.filter(course__teacher_id=teacher_id)

            if enrollment_status:
                queryset = queryset.filter(status=enrollment_status)

            if semester:
                queryset = queryset.filter(course__semester=semester)

            if grade_status:
                if grade_status == 'graded':
                    queryset = queryset.filter(total_score__isnull=False)
                elif grade_status == 'ungraded':
                    queryset = queryset.filter(total_score__isnull=True)

            # 排序
            if ordering:
                queryset = queryset.order_by(ordering)
            else:
                queryset = queryset.order_by('-enrollment_date')

            # 计算总数
            total = queryset.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            enrollments = queryset[start:end]

            # 序列化数据
            serializer = AdminEnrollmentListSerializer(enrollments, many=True)

            response_data = {
                'enrollments': serializer.data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }

            return Response({
                'code': 200,
                'message': '获取选课记录成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取选课记录失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取选课记录失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class EnrollmentDetailView(APIView):
    """选课详情视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request, enrollment_id):
        """获取选课详情"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            try:
                enrollment = Enrollment.objects.select_related(
                    'course', 'course__teacher', 'student', 'grade_entered_by'
                ).get(id=enrollment_id)
            except Enrollment.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '选课记录不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 权限检查
            if user_role == 'student' and enrollment.student_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能查看自己的选课记录'
                }, status=status.HTTP_403_FORBIDDEN)
            elif user_role == 'teacher' and enrollment.course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能查看自己课程的选课记录'
                }, status=status.HTTP_403_FORBIDDEN)

            serializer = EnrollmentDetailSerializer(enrollment)

            return Response({
                'code': 200,
                'message': '获取选课详情成功',
                'data': serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取选课详情失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取选课详情失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class GradeEntryView(APIView):
    """成绩录入视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request, enrollment_id):
        """录入或修改成绩"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role not in ['teacher', 'admin']:
                return Response({
                    'code': 403,
                    'message': '只有教师和管理员可以录入成绩'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                enrollment = Enrollment.objects.select_related('course', 'student').get(id=enrollment_id)
            except Enrollment.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '选课记录不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 权限检查
            if user_role == 'teacher' and enrollment.course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能为自己课程的学生录入成绩'
                }, status=status.HTTP_403_FORBIDDEN)

            if enrollment.status != 'enrolled':
                return Response({
                    'code': 400,
                    'message': '只能为已选课状态的学生录入成绩'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 验证成绩数据
            serializer = EnrollmentGradeSerializer(data=request.data)
            if not serializer.is_valid():
                return Response({
                    'code': 400,
                    'message': '成绩数据验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            # 更新成绩
            with transaction.atomic():
                for field, value in serializer.validated_data.items():
                    setattr(enrollment, field, value)

                enrollment.grade_entered_by_id = user_id
                enrollment.grade_entered_at = timezone.now()
                enrollment.save()

            return Response({
                'code': 200,
                'message': '录入成绩成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"录入成绩失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '录入成绩失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class BatchGradeEntryView(APIView):
    """批量成绩录入视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """批量录入成绩"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role not in ['teacher', 'admin']:
                return Response({
                    'code': 403,
                    'message': '只有教师和管理员可以录入成绩'
                }, status=status.HTTP_403_FORBIDDEN)

            enrollment_ids = request.data.get('enrollment_ids', [])
            grade_data = request.data.get('grade_data', {})

            if not enrollment_ids:
                return Response({
                    'code': 400,
                    'message': '请选择要录入成绩的学生'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 验证成绩数据
            serializer = EnrollmentGradeSerializer(data=grade_data)
            if not serializer.is_valid():
                return Response({
                    'code': 400,
                    'message': '成绩数据验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取选课记录
            enrollments = Enrollment.objects.select_related('course').filter(id__in=enrollment_ids)

            if len(enrollments) != len(enrollment_ids):
                return Response({
                    'code': 400,
                    'message': '部分选课记录不存在'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 权限检查
            if user_role == 'teacher':
                invalid_enrollments = enrollments.exclude(course__teacher_id=int(user_id))
                if invalid_enrollments.exists():
                    return Response({
                        'code': 403,
                        'message': '只能为自己课程的学生录入成绩'
                    }, status=status.HTTP_403_FORBIDDEN)

            # 检查状态
            invalid_status = enrollments.exclude(status='enrolled')
            if invalid_status.exists():
                return Response({
                    'code': 400,
                    'message': '只能为已选课状态的学生录入成绩'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 批量更新成绩
            success_count = 0
            with transaction.atomic():
                for enrollment in enrollments:
                    for field, value in serializer.validated_data.items():
                        setattr(enrollment, field, value)

                    enrollment.grade_entered_by_id = user_id
                    enrollment.grade_entered_at = timezone.now()
                    enrollment.save()
                    success_count += 1

            return Response({
                'code': 200,
                'message': f'批量录入成绩成功，共处理 {success_count} 条记录'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"批量录入成绩失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '批量录入成绩失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class MarkCompletedView(APIView):
    """标记完成视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request, enrollment_id):
        """标记课程完成"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role not in ['teacher', 'admin']:
                return Response({
                    'code': 403,
                    'message': '只有教师和管理员可以标记完成'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                enrollment = Enrollment.objects.select_related('course').get(id=enrollment_id)
            except Enrollment.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '选课记录不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 权限检查
            if user_role == 'teacher' and enrollment.course.teacher_id != int(user_id):
                return Response({
                    'code': 403,
                    'message': '只能标记自己课程的学生'
                }, status=status.HTTP_403_FORBIDDEN)

            if enrollment.status != 'enrolled':
                return Response({
                    'code': 400,
                    'message': '只能标记已选课状态的学生为完成'
                }, status=status.HTTP_400_BAD_REQUEST)

            if enrollment.total_score is None:
                return Response({
                    'code': 400,
                    'message': '必须先录入成绩才能标记完成'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 标记完成
            with transaction.atomic():
                enrollment.status = 'completed'
                enrollment.save()

            return Response({
                'code': 200,
                'message': '标记完成成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"标记完成失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '标记完成失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class BatchMarkCompletedView(APIView):
    """批量标记完成视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """批量标记完成"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role not in ['teacher', 'admin']:
                return Response({
                    'code': 403,
                    'message': '只有教师和管理员可以标记完成'
                }, status=status.HTTP_403_FORBIDDEN)

            enrollment_ids = request.data.get('enrollment_ids', [])

            if not enrollment_ids:
                return Response({
                    'code': 400,
                    'message': '请选择要标记完成的学生'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取选课记录
            enrollments = Enrollment.objects.select_related('course').filter(id__in=enrollment_ids)

            if len(enrollments) != len(enrollment_ids):
                return Response({
                    'code': 400,
                    'message': '部分选课记录不存在'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 权限检查
            if user_role == 'teacher':
                invalid_enrollments = enrollments.exclude(course__teacher_id=int(user_id))
                if invalid_enrollments.exists():
                    return Response({
                        'code': 403,
                        'message': '只能标记自己课程的学生'
                    }, status=status.HTTP_403_FORBIDDEN)

            # 状态和成绩检查
            invalid_status = enrollments.exclude(status='enrolled')
            if invalid_status.exists():
                return Response({
                    'code': 400,
                    'message': '只能标记已选课状态的学生为完成'
                }, status=status.HTTP_400_BAD_REQUEST)

            no_grade = enrollments.filter(total_score__isnull=True)
            if no_grade.exists():
                return Response({
                    'code': 400,
                    'message': '必须先录入成绩才能标记完成'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 批量标记完成
            success_count = 0
            with transaction.atomic():
                for enrollment in enrollments:
                    enrollment.status = 'completed'
                    enrollment.save()
                    success_count += 1

            return Response({
                'code': 200,
                'message': f'批量标记完成成功，共处理 {success_count} 条记录'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"批量标记完成失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '批量标记完成失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class AdminForceDropEnrollmentView(APIView):
    """管理员强制退课"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request, enrollment_id):
        """强制退课"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '只有管理员可以强制退课'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                enrollment = Enrollment.objects.get(id=enrollment_id)
            except Enrollment.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '选课记录不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            if enrollment.status != 'enrolled':
                return Response({
                    'code': 400,
                    'message': '只能强制退选已选课状态的记录'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 执行强制退课
            with transaction.atomic():
                enrollment.status = 'dropped'
                enrollment.remarks = f"管理员强制退课 - 操作人: {user_id} - 时间: {timezone.now()}"
                enrollment.save()

                # 更新课程选课人数
                course = enrollment.course
                course.enrolled_count = Enrollment.objects.filter(
                    course=course,
                    status='enrolled'
                ).count()
                course.save(update_fields=['enrolled_count'])

            return Response({
                'code': 200,
                'message': '强制退课成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"强制退课失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '强制退课失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class BatchForceDropView(APIView):
    """批量强制退课视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """批量强制退课"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '只有管理员可以强制退课'
                }, status=status.HTTP_403_FORBIDDEN)

            enrollment_ids = request.data.get('enrollment_ids', [])

            if not enrollment_ids:
                return Response({
                    'code': 400,
                    'message': '请选择要强制退课的学生'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取选课记录
            enrollments = Enrollment.objects.select_related('course').filter(id__in=enrollment_ids)

            if len(enrollments) != len(enrollment_ids):
                return Response({
                    'code': 400,
                    'message': '部分选课记录不存在'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 状态检查
            invalid_status = enrollments.exclude(status='enrolled')
            if invalid_status.exists():
                return Response({
                    'code': 400,
                    'message': '只能强制退选已选课状态的学生'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 批量强制退课
            success_count = 0
            updated_courses = set()

            with transaction.atomic():
                for enrollment in enrollments:
                    enrollment.status = 'dropped'
                    enrollment.remarks = f"管理员批量强制退课 - 操作人: {user_id} - 时间: {timezone.now()}"
                    enrollment.save()
                    updated_courses.add(enrollment.course_id)
                    success_count += 1

                # 更新相关课程的选课人数
                for course_id in updated_courses:
                    course = Course.objects.get(id=course_id)
                    course.enrolled_count = Enrollment.objects.filter(
                        course=course,
                        status='enrolled'
                    ).count()
                    course.save(update_fields=['enrolled_count'])

            return Response({
                'code': 200,
                'message': f'批量强制退课成功，共处理 {success_count} 条记录'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"批量强制退课失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '批量强制退课失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class AdminResetGradeView(APIView):
    """管理员重置成绩"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request, enrollment_id):
        """重置成绩"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '只有管理员可以重置成绩'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                enrollment = Enrollment.objects.get(id=enrollment_id)
            except Enrollment.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '选课记录不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            if enrollment.total_score is None:
                return Response({
                    'code': 400,
                    'message': '该记录没有成绩，无需重置'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 重置成绩
            with transaction.atomic():
                enrollment.attendance_score = None
                enrollment.homework_score = None
                enrollment.midterm_score = None
                enrollment.final_score = None
                enrollment.total_score = None
                enrollment.grade = None
                enrollment.grade_entered_by = None
                enrollment.grade_entered_at = None
                enrollment.remarks = f"管理员重置成绩 - 操作人: {user_id} - 时间: {timezone.now()}"
                enrollment.save()

            return Response({
                'code': 200,
                'message': '重置成绩成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"重置成绩失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '重置成绩失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class EnrollmentStatisticsView(APIView):
    """选课统计视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取选课统计数据"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            # 基础查询集
            queryset = Enrollment.objects.all()

            # 根据角色过滤数据
            if user_role == 'teacher':
                queryset = queryset.filter(course__teacher_id=user_id)
            elif user_role == 'student':
                return Response({
                    'code': 403,
                    'message': '学生无权查看统计数据'
                }, status=status.HTTP_403_FORBIDDEN)

            # 基础统计
            total_enrollments = queryset.count()
            active_enrollments = queryset.filter(status='enrolled').count()
            completed_enrollments = queryset.filter(status='completed').count()
            dropped_enrollments = queryset.filter(status='dropped').count()

            # 成绩分布统计
            grade_distribution = {
                'A': queryset.filter(grade='A').count(),
                'B': queryset.filter(grade='B').count(),
                'C': queryset.filter(grade='C').count(),
                'D': queryset.filter(grade='D').count(),
                'F': queryset.filter(grade='F').count(),
            }

            # 按学期统计
            semester_stats = queryset.values('course__semester').annotate(
                count=Count('id'),
                avg_score=Avg('total_score')
            ).order_by('-course__semester')

            # 按课程统计（仅管理员）
            course_stats = []
            if user_role == 'admin':
                course_stats = queryset.values(
                    'course__course_name',
                    'course__course_code'
                ).annotate(
                    total_students=Count('id'),
                    enrolled_students=Count('id', filter=Q(status='enrolled')),
                    completed_students=Count('id', filter=Q(status='completed')),
                    avg_score=Avg('total_score')
                ).order_by('-total_students')[:10]  # 前10门课程

            response_data = {
                'total_enrollments': total_enrollments,
                'active_enrollments': active_enrollments,
                'completed_enrollments': completed_enrollments,
                'dropped_enrollments': dropped_enrollments,
                'grade_distribution': grade_distribution,
                'semester_stats': list(semester_stats),
                'course_stats': list(course_stats)
            }

            return Response({
                'code': 200,
                'message': '获取统计数据成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取统计数据失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取统计数据失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class EnrollmentExportView(APIView):
    """选课数据导出视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """导出选课数据"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取查询参数
            student_search = request.GET.get('student_search', '').strip()
            course_search = request.GET.get('course_search', '').strip()
            teacher_id = request.GET.get('teacher_id', '')
            enrollment_status = request.GET.get('status', '')
            semester = request.GET.get('semester', '')
            grade_status = request.GET.get('grade_status', '')

            # 构建查询集
            queryset = Enrollment.objects.select_related(
                'course', 'course__teacher', 'student', 'grade_entered_by'
            )

            # 根据角色过滤
            if user_role == 'teacher':
                queryset = queryset.filter(course__teacher_id=user_id)

            # 应用筛选条件
            if student_search:
                queryset = queryset.filter(
                    Q(student__real_name__icontains=student_search) |
                    Q(student__student_id__icontains=student_search)
                )

            if course_search:
                queryset = queryset.filter(
                    Q(course__course_name__icontains=course_search) |
                    Q(course__course_code__icontains=course_search)
                )

            if teacher_id:
                queryset = queryset.filter(course__teacher_id=teacher_id)

            if enrollment_status:
                queryset = queryset.filter(status=enrollment_status)

            if semester:
                queryset = queryset.filter(course__semester=semester)

            if grade_status:
                if grade_status == 'graded':
                    queryset = queryset.filter(total_score__isnull=False)
                elif grade_status == 'ungraded':
                    queryset = queryset.filter(total_score__isnull=True)

            queryset = queryset.order_by('-enrollment_date')

            # 创建Excel文件
            workbook = openpyxl.Workbook()
            worksheet = workbook.active
            worksheet.title = "选课数据"

            # 设置标题样式
            title_font = Font(bold=True, color="FFFFFF")
            title_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
            title_alignment = Alignment(horizontal="center", vertical="center")

            # 定义表头
            headers = []
            if user_role == 'admin' or user_role == 'teacher':
                headers.extend(['学生姓名', '学号', '院系'])

            headers.extend([
                '课程编号', '课程名称', '学分', '学期'
            ])

            if user_role == 'admin':
                headers.append('授课教师')

            headers.extend([
                '选课状态', '考勤成绩', '作业成绩', '期中成绩',
                '期末成绩', '总成绩', '等级成绩', '选课时间', '备注'
            ])

            # 写入表头
            for col, header in enumerate(headers, 1):
                cell = worksheet.cell(row=1, column=col, value=header)
                cell.font = title_font
                cell.fill = title_fill
                cell.alignment = title_alignment

            # 写入数据
            for row_idx, enrollment in enumerate(queryset, 2):
                col_idx = 1

                # 学生信息（管理员和教师可见）
                if user_role == 'admin' or user_role == 'teacher':
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.student.real_name)
                    col_idx += 1
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.student.student_id)
                    col_idx += 1
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.student.department or '')
                    col_idx += 1

                # 课程信息
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.course_code)
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.course_name)
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.credit_hours)
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.semester)
                col_idx += 1

                # 教师信息（仅管理员可见）
                if user_role == 'admin':
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.teacher.real_name)
                    col_idx += 1

                # 选课和成绩信息
                status_display = dict(Enrollment.STATUS_CHOICES).get(enrollment.status, enrollment.status)
                worksheet.cell(row=row_idx, column=col_idx, value=status_display)
                col_idx += 1

                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.attendance_score) if enrollment.attendance_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.homework_score) if enrollment.homework_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.midterm_score) if enrollment.midterm_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.final_score) if enrollment.final_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.total_score) if enrollment.total_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.grade or '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=enrollment.enrollment_date.strftime('%Y-%m-%d %H:%M:%S'))
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.remarks or '')

            # 调整列宽
            for column in worksheet.columns:
                max_length = 0
                column_letter = column[0].column_letter
                for cell in column:
                    try:
                        if len(str(cell.value)) > max_length:
                            max_length = len(str(cell.value))
                    except:
                        pass
                adjusted_width = min(max_length + 2, 50)
                worksheet.column_dimensions[column_letter].width = adjusted_width

            # 保存到内存
            excel_file = BytesIO()
            workbook.save(excel_file)
            excel_file.seek(0)

            # 创建HTTP响应
            response = HttpResponse(
                excel_file.read(),
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )

            filename = f"选课数据_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
            response['Content-Disposition'] = f'attachment; filename="{filename}"'

            return response

        except Exception as e:
            logger.error(f"导出数据失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '导出数据失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class BatchExportView(APIView):
    """批量导出选课数据视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """批量导出选中的选课数据"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role not in ['admin', 'teacher']:
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            enrollment_ids = request.data.get('enrollment_ids', [])

            if not enrollment_ids:
                return Response({
                    'code': 400,
                    'message': '请选择要导出的数据'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取选课记录
            queryset = Enrollment.objects.select_related(
                'course', 'course__teacher', 'student', 'grade_entered_by'
            ).filter(id__in=enrollment_ids)

            # 权限检查
            if user_role == 'teacher':
                queryset = queryset.filter(course__teacher_id=user_id)

            queryset = queryset.order_by('-enrollment_date')

            # 创建Excel文件（使用相同的导出逻辑）
            workbook = openpyxl.Workbook()
            worksheet = workbook.active
            worksheet.title = "选中选课数据"

            # 设置标题样式
            title_font = Font(bold=True, color="FFFFFF")
            title_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
            title_alignment = Alignment(horizontal="center", vertical="center")

            # 定义表头
            headers = []
            if user_role == 'admin' or user_role == 'teacher':
                headers.extend(['学生姓名', '学号', '院系'])

            headers.extend([
                '课程编号', '课程名称', '学分', '学期'
            ])

            if user_role == 'admin':
                headers.append('授课教师')

            headers.extend([
                '选课状态', '考勤成绩', '作业成绩', '期中成绩',
                '期末成绩', '总成绩', '等级成绩', '选课时间', '备注'
            ])

            # 写入表头
            for col, header in enumerate(headers, 1):
                cell = worksheet.cell(row=1, column=col, value=header)
                cell.font = title_font
                cell.fill = title_fill
                cell.alignment = title_alignment

            # 写入数据
            for row_idx, enrollment in enumerate(queryset, 2):
                col_idx = 1

                # 学生信息（管理员和教师可见）
                if user_role == 'admin' or user_role == 'teacher':
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.student.real_name)
                    col_idx += 1
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.student.student_id)
                    col_idx += 1
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.student.department or '')
                    col_idx += 1

                # 课程信息
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.course_code)
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.course_name)
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.credit_hours)
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.semester)
                col_idx += 1

                # 教师信息（仅管理员可见）
                if user_role == 'admin':
                    worksheet.cell(row=row_idx, column=col_idx, value=enrollment.course.teacher.real_name)
                    col_idx += 1

                # 选课和成绩信息
                status_display = dict(Enrollment.STATUS_CHOICES).get(enrollment.status, enrollment.status)
                worksheet.cell(row=row_idx, column=col_idx, value=status_display)
                col_idx += 1

                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.attendance_score) if enrollment.attendance_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.homework_score) if enrollment.homework_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.midterm_score) if enrollment.midterm_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.final_score) if enrollment.final_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=float(enrollment.total_score) if enrollment.total_score else '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.grade or '')
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx,
                               value=enrollment.enrollment_date.strftime('%Y-%m-%d %H:%M:%S'))
                col_idx += 1
                worksheet.cell(row=row_idx, column=col_idx, value=enrollment.remarks or '')

            # 调整列宽
            for column in worksheet.columns:
                max_length = 0
                column_letter = column[0].column_letter
                for cell in column:
                    try:
                        if len(str(cell.value)) > max_length:
                            max_length = len(str(cell.value))
                    except:
                        pass
                adjusted_width = min(max_length + 2, 50)
                worksheet.column_dimensions[column_letter].width = adjusted_width

            # 保存到内存
            excel_file = BytesIO()
            workbook.save(excel_file)
            excel_file.seek(0)

            # 创建HTTP响应
            response = HttpResponse(
                excel_file.read(),
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )

            filename = f"选中选课数据_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
            response['Content-Disposition'] = f'attachment; filename="{filename}"'

            return response

        except Exception as e:
            logger.error(f"批量导出数据失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '批量导出数据失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class StudentCourseStatusView(APIView):
    """获取学生的课程选课状态（批量）"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """批量获取课程的选课状态"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'student':
                return Response({
                    'code': 403,
                    'message': '只有学生可以查询选课状态'
                }, status=status.HTTP_403_FORBIDDEN)

            course_ids = request.data.get('course_ids', [])
            if not course_ids:
                return Response({
                    'code': 400,
                    'message': '课程ID列表不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取课程信息
            courses = Course.objects.filter(id__in=course_ids)
            course_dict = {course.id: course for course in courses}

            # 获取选课记录
            enrollments = Enrollment.objects.filter(
                student_id=user_id,
                course_id__in=course_ids
            ).select_related('course')

            enrollment_dict = {enrollment.course_id: enrollment for enrollment in enrollments}

            # 构建结果
            course_status = {}
            for course_id in course_ids:
                course = course_dict.get(course_id)
                if not course:
                    continue

                enrollment = enrollment_dict.get(course_id)

                can_enroll = False
                can_drop = False
                enrollment_status = 'not_enrolled'
                message = ''
                enrollment_date = None

                if not enrollment or enrollment.status == 'dropped':
                    # 未选课或已退选
                    if course.status != 'active':
                        message = '课程未开放选课'
                    elif course.enrolled_count >= course.capacity:
                        message = '课程已满员'
                    else:
                        can_enroll = True
                        message = '可以选课'
                    enrollment_status = 'not_enrolled'
                elif enrollment.status == 'enrolled':
                    # 已选课
                    if enrollment.total_score is not None:
                        message = '已有成绩，不能退选'
                    else:
                        can_drop = True
                        message = '可以退选'
                    enrollment_status = 'enrolled'
                    enrollment_date = enrollment.enrollment_date.strftime('%Y-%m-%d %H:%M:%S')
                elif enrollment.status == 'completed':
                    # 已完成
                    message = '课程已完成'
                    enrollment_status = 'completed'
                    enrollment_date = enrollment.enrollment_date.strftime('%Y-%m-%d %H:%M:%S')

                course_status[course_id] = {
                    'can_enroll': can_enroll,
                    'can_drop': can_drop,
                    'status': enrollment_status,
                    'message': message,
                    'enrollment_date': enrollment_date
                }

            return Response({
                'code': 200,
                'message': '获取选课状态成功',
                'data': course_status
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取选课状态失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取选课状态失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class CourseEnrollmentStatusView(APIView):
    """课程选课状态检查视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request, course_id):
        """检查学生对某门课程的选课状态"""
        try:
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if user_role != 'student':
                return Response({
                    'code': 200,
                    'message': '非学生用户',
                    'data': {
                        'can_enroll': False,
                        'can_drop': False,
                        'status': 'not_student',
                        'message': '非学生用户'
                    }
                }, status=status.HTTP_200_OK)

            try:
                course = Course.objects.get(id=course_id)
            except Course.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '课程不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 检查选课记录
            enrollment = Enrollment.objects.filter(
                student_id=user_id,
                course_id=course_id
            ).first()

            can_enroll = False
            can_drop = False
            enrollment_status = 'not_enrolled'
            message = ''

            if not enrollment or enrollment.status == 'dropped':
                # 未选课或已退选
                if course.status != 'active':
                    message = '课程未开放选课'
                elif course.enrolled_count >= course.capacity:
                    message = '课程已满员'
                else:
                    can_enroll = True
                    message = '可以选课'
                enrollment_status = 'not_enrolled'
            elif enrollment.status == 'enrolled':
                # 已选课
                if enrollment.total_score is not None:
                    message = '已有成绩，不能退选'
                else:
                    can_drop = True
                    message = '可以退选'
                enrollment_status = 'enrolled'
            elif enrollment.status == 'completed':
                # 已完成
                message = '课程已完成'
                enrollment_status = 'completed'

            return Response({
                'code': 200,
                'message': '获取选课状态成功',
                'data': {
                    'can_enroll': can_enroll,
                    'can_drop': can_drop,
                    'status': enrollment_status,
                    'message': message,
                    'enrollment_date': enrollment.enrollment_date.strftime('%Y-%m-%d %H:%M:%S') if enrollment else None
                }
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取选课状态失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取选课状态失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)